
//

import UIKit
import SVProgressHUD

class CZOauthViewController: UIViewController {
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
   
        self.view.backgroundColor = UIColor.whiteColor()
        //设置导航栏
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        //title
        navigationItem.title = "登录"
        //使用webview加载登录界面
        
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        print("\(urlString)")
     let url = NSURL(string: urlString)
       let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        //加指示器，显示正在加载
        SVProgressHUD.showWithStatus("正在加载")
        
    }

    
    
    //MARK : -点击事件
    @objc private func autoFill()
    {
        let jsString = "document.getElementById('userId').value='13590052607';document.getElementById('passwd').value='drawhuayan.';"
         // 使用WebView执行JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    @objc private func close ()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //懒加载
    private lazy var webView:UIWebView = UIWebView()

}
extension CZOauthViewController:UIWebViewDelegate
{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!
        CZPrint(items: "request: \(url.absoluteString)")
//      print("request===========\(url.absoluteString)")
        //只要不是授权回调地址，是新浪的界面，就让他去加载
        if !url.absoluteString.hasPrefix(redirect_uri)
        {
            return true
        }else
        {
            let query = url.query!
            let codeString = "code="
            if query.hasPrefix(codeString)
            {
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                CZPrint(items: "code: \(code)")
                CZUserAccountViewModel.shareIntance.loadAcessToken(code, callback: { (error) -> () in
                    if error != nil {
                    
                        //出现错误
                        CZPrint(items: "\(error)")
                        SVProgressHUD.showErrorWithStatus("您的网络不给力")
                        
                    }else{
                        //延迟一秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                            //跳转到CZWelcomeViewCotroller
                            let appDelegate =  (UIApplication.sharedApplication().delegate as! AppDelegate)
                           
                            appDelegate.switchRootViewController(CZWelcomeViewController())
                        })
                    }
                    
                })

            }else
            {
                close()
            }
            return false
        }
        
        
    }
}